using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Localization;
using Microsoft.VisualBasic;

namespace Code5Systems.FormMaster
{

	public partial class Download : System.Web.UI.Page
	{
		
#region  Web Form Designer Generated Code
		
		//Protected WithEvents hlClose As System.Web.UI.WebControls.HyperLink
		
		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent()
		{
			
		}
		
		protected System.Web.UI.WebControls.DataGrid dgExcel;
		protected System.Web.UI.WebControls.HyperLink hlClose;
		protected System.Web.UI.WebControls.Panel pnlNotAuth;
		protected System.Web.UI.WebControls.Label lblNotAuthorized;
		
		//NOTE: The following placeholder declaration is required by the Web Form Designer.
		//Do not delete or move it.
		private System.Object designerPlaceholderDeclaration;
		
		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();
			//Thread.CurrentThread.CurrentUICulture = New CultureInfo("he-IL")
		}
		
#endregion
		
		
#region Private Members
		
		private string downloadType = "csv";
		private int _portalID = -1;
		private int _moduleID = -1;
		private int _tabId = -1;
		private bool _bIsAdmin = false;
		private bool bAuthorized = false;
		private int intDealerId = int.MaxValue;
		private DateTime dtStart = DateTime.MinValue;
		private DateTime dtEnd;
		
#endregion
		
		
#region Event Handlers
		
		private void Page_Load(System.Object sender, System.EventArgs e)
		{
			
			if (Information.IsNumeric(Request.Params["mid"]))
			{
				_moduleID = System.Convert.ToInt32(Request.Params["mid"]);
			}
			
			if (Information.IsNumeric(Request.Params["tabid"]))
			{
				_tabId = System.Convert.ToInt32(Request.Params["tabid"]);
			}
			
			if (Information.IsNumeric(Request.Params["portid"]))
			{
				_portalID = System.Convert.ToInt32(Request.Params["portid"]);
			}
			
			if (Request.QueryString["type"] != string.Empty)
			{
				downloadType = Request.QueryString["type"];
			}
			
			this.pnlNotAuth.Visible = false;
			
			//Verify that the user is allowed to accesss this page since
			//we are out of the scope of the DNN Security system
			UserInfo objUser = default(UserInfo);
			
			UserController objUserCtl = new UserController();
			if (Context.User.Identity.IsAuthenticated)
			{
				ModuleController objModuleController = new ModuleController();
				ModuleInfo objModuleInfo = objModuleController.GetModule(_moduleID, _tabId);
				
				objUser = UserController.GetUserByName(_portalID, Context.User.Identity.Name);
				
				if (objUser.IsSuperUser || objUser.IsInRole("Administrators"))
				{
					bAuthorized = true;
				}
				else
				{
					int iIndex = default(int);
					
					ModulePermissionCollection permissions = ModulePermissionController.GetModulePermissions(_moduleID, _tabId);
					
					List<string> editRoles = new List<string>();
					
					foreach (ModulePermissionInfo permission in permissions)
					{
						if (permission.AllowAccess)
						{
							if (permission.PermissionKey == "EDIT")
							{
								if (permission.UserID == objUser.UserID)
								{
									bAuthorized = true;
									break;
								}
								editRoles.Add(permission.RoleName);
							}
						}
					}
					
					if (!bAuthorized)
					{
						DotNetNuke.Security.Roles.RoleController objRoleController = new DotNetNuke.Security.Roles.RoleController();
						
						string[] aryUserRoles = objRoleController.GetRolesByUser(objUser.UserID, _portalID);
						
						if (aryUserRoles != null)
						{
							for (iIndex = 0; iIndex <= aryUserRoles.Length - 1; iIndex++)
							{
								if (editRoles.Contains(aryUserRoles[iIndex]))
								{
									bAuthorized = true;
									break;
								}
							}
						}
					}
					
				}
				
				CultureInfo userCulture = Utility.GetUserCulture();
				
				if (dtStart == DateTime.MinValue)
				{
					try
					{
						if (Request.QueryString["sdate"] != string.Empty)
						{
							string dtString = Request.QueryString["sdate"];
							dtStart = DateTime.Parse(Request.QueryString["sdate"], userCulture);
						}
						
						if (Request.QueryString["edate"] != string.Empty)
						{
							dtEnd = System.Convert.ToDateTime(DateTime.Parse(Request.QueryString["edate"], userCulture).AddDays(1).AddSeconds(-1));
						}
					}
					catch
					{
						
					}
				}
			}
		}
		
		protected override void Render(System.Web.UI.HtmlTextWriter writer)
		{
			Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
			
			if (bAuthorized)
			{
				
				try
				{
					Encoding enc = Encoding.GetEncoding(System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage);
					
					string strFileName = default(string);
					DataSet ds = objFormDataCtl.List(_moduleID, dtStart, dtEnd, 1, int.MaxValue, this.TemplateSourceDirectory + "/", false);
					
					Code5Systems.FormMaster.Business.FormController objFormCtl = new Code5Systems.FormMaster.Business.FormController(_moduleID);
					strFileName = objFormCtl.FormInfo.FormName.Replace(" ", "-");
					
					//strFileName = "FormData"
					
					DataTable dt = ds.Tables[0];
					switch (downloadType)
					{
						case "xl7":
							//Since Excel 2002+ can open HTML tables just output the datagrid
							this.dgExcel.Visible = true;
							this.dgExcel.DataSource = dt;
							this.dgExcel.DataBind();
							strFileName += ".xls";
							Response.ContentType = "application/ms-excel";
							//Response.ContentEncoding = Encoding.UTF7
							Response.Charset = enc.BodyName;
							Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
							this.dgExcel.RenderControl(writer);
							break;
						case "xl":
							//Since Excel 2002+ can open HTML tables just output the datagrid
							this.dgExcel.Visible = true;
							this.dgExcel.DataSource = dt;
							this.dgExcel.DataBind();
							strFileName += ".xls";
							Response.ContentType = "application/ms-excel";
							Response.ContentEncoding = Encoding.UTF7;
							Response.Charset = enc.BodyName;
							Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
							this.dgExcel.RenderControl(writer);
							break;
						case "tab":
							//Plain Text Tab Delimited
							this.dgExcel.Visible = false;
							strFileName += ".txt";
							Response.ContentType = "text/plain";
							Response.ContentEncoding = Encoding.UTF8;
							Response.Charset = enc.BodyName;
							Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
							ConvertDtToTDF(dt);
							break;
						case "csv":
							//Plain text CSV
							this.dgExcel.Visible = false;
							strFileName += ".csv";
							Response.ContentType = "text/plain";
							Response.ContentEncoding = Encoding.UTF8;
							Response.Charset = enc.BodyName;
							Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
							ConvertDtToCSV(dt);
							break;
					}
					
				}
				catch (Exception ex)
				{
					Response.Write("<p>" + ex.Message + "</p><p>Please Use your Browser Back button to Return</p>");
				}
				
			}
			else
			{
				this.dgExcel.Visible = false;
				this.pnlNotAuth.Visible = true;
				this.lblNotAuthorized.Text = Localization.GetString("AccessDenied", objFormDataCtl.SharedResouceFile);
				base.Render(writer);
			}
			
		}
		
#endregion
		
		
#region Helper Methods
		
		//Converts a DataTable to Tab Delimited Format
		private void ConvertDtToTDF(DataTable dt)
		{
			DataRow dr = default(DataRow);
			object[] ary = null;
			int i = default(int);
			int iCol = default(int);
			string strData = default(string);
			
			//Output Column Headers
			for (iCol = 0; iCol <= dt.Columns.Count - 1; iCol++)
			{
				Response.Write(dt.Columns[iCol].ToString());
				if (iCol < dt.Columns.Count - 1)
				{
					Response.Write(Microsoft.VisualBasic.Constants.vbTab);
				}
			}
			Response.Write(Microsoft.VisualBasic.Constants.vbCrLf);
			
			//Output Data
			for (int r = 0; r <= dt.Rows.Count - 1; r++)
			{
				dr = dt.Rows[r];
				ary = dr.ItemArray;
				for (i = 0; i <= (ary.Length - 1); i++)
				{
					strData = (string) (ary[i].ToString());
					strData = strData.Replace(Microsoft.VisualBasic.Constants.vbLf, "");
					strData = strData.Replace(Microsoft.VisualBasic.Constants.vbCr, "");
					Response.Write(strData);
					if (i < (ary.Length - 1))
					{
						Response.Write(Microsoft.VisualBasic.Constants.vbTab);
					}
				}
				if (r < dt.Rows.Count - 1)
				{
					Response.Write(Microsoft.VisualBasic.Constants.vbCrLf);
				}
			}
		}
		
		//Converts a DataTable to CSV Format
		private void ConvertDtToCSV(DataTable dt)
		{
			DataRow dr = default(DataRow);
			object[] ary = null;
			int i = default(int);
			int iCol = default(int);
			string strData = default(string);
			
			//Output Column Headers
			for (iCol = 0; iCol <= dt.Columns.Count - 1; iCol++)
			{
				Response.Write("\"" + dt.Columns[iCol].ToString() + "\"");
				if (iCol < dt.Columns.Count - 1)
				{
					Response.Write(",");
				}
			}
			Response.Write(Microsoft.VisualBasic.Constants.vbCrLf);
			
			//Output Data
			for (int r = 0; r <= dt.Rows.Count - 1; r++)
			{
				dr = dt.Rows[r];
				ary = dr.ItemArray;
				for (i = 0; i <= (ary.Length - 1); i++)
				{
					strData = (string) (ary[i].ToString());
					strData = strData.Replace(Microsoft.VisualBasic.Constants.vbLf, "");
					strData = strData.Replace(Microsoft.VisualBasic.Constants.vbCr, "");
					Response.Write("\"" + strData + "\"");
					if (i < (ary.Length - 1))
					{
						Response.Write(",");
					}
				}
				if (r < dt.Rows.Count - 1)
				{
					Response.Write(Microsoft.VisualBasic.Constants.vbCrLf);
				}
			}
		}
		
#endregion
		
		
	}
	
	
	
}

